package com.example.demo.service.impl;

import com.example.demo.common.Constant;
import com.example.demo.dao.UserDao;
import com.example.demo.dto.UserDto;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.Base64Util;
import com.example.demo.utils.RedisUtil;
import com.example.demo.utils.TokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RedisUtil redisUtil;
 /*   @Override
    public User login(String username, String password) {
        System.out.println("susername="+username+",spassword="+password);
//        return userDao.findUserByUsernameAndPassword(username,password);

        return userDao.findUserByUsername(username);
    }*/

        @Override
    public UserDto login(String username, String password) {
        System.out.println("susername="+username+",spassword="+password);
//        return userDao.findUserByUsernameAndPassword(username,password);
//            User user = userDao.findUserByUsername(username);
            User user = userDao.findUserByUsernameAndPassword(username,password);
        UserDto userDto=null;
        if(user!=null){
            userDto = new UserDto();
            BeanUtils.copyProperties(user,userDto);
        }

        return userDto;
    }

    @Override
    public boolean checkToken(long userid, String token) {
        return false;
    }

    @Override
    public boolean checkToken(long userid, String token, String clientType) {
        if(clientType==null || clientType.isEmpty()){
            clientType = Constant.CLIENT_TYPE_WEB;
        }
        Object o = redisUtil.hget(Constant.TOKEN_KEY_PREFIX +userid,clientType);
        if(o!=null){
            return true;
        }
        return false;
    }

    @Override
    public String generateToken(UserDto userDto, String clientType) throws UnsupportedEncodingException {
        String tokenKey = "token:"+userDto.getId();
        Map<String, Object> map = new HashMap();
        String tokenValue = TokenUtil.generateTokenValue(clientType,userDto.getId());
        map.put(clientType, tokenValue);
        redisUtil.hmset(tokenKey,map,Constant.TOKEN_EXPIRE_TIME);
        String token =  Base64Util.encode(userDto.getId()+"-"+tokenValue);
        return token;
    }
}
